import urllib.request, urllib.parse, urllib.error
import http.cookiejar
import urllib.request

import requests

from util import utils

URL_ROOT = r'http://d.weibo.com/'
MAC_HEADER = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) ' \
             'Chrome/71.0.3559.6 Safari/537.36 '
WIN_HEADER = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'


def httpRequest():
    headers = {'User-Agent': WIN_HEADER}
    postdata = {"data": 1}
    cookie = http.cookiejar.CookieJar()

    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)

    request = urllib.request.Request(URL_ROOT, headers)
    urllib.request.urlopen(request)
    for item in cookie:
        print('Name = ' + item.name)
        print('Value = ' + item.value)
    return


def setCookie():
    URL_ROOT = 'http://94.91p31.space/login.php'
    values = {'username': 'cpcxy', 'password': 'cp896446',
              'fingerprint':'819058456',
              'fingerprint2':'b5e58ae3ec426e44a84d40d201f9d10d'}
    postdata = urllib.parse.urlencode(values).encode()
    user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 ' \
                 r'Safari/537.36 '
    headers = {'User-Agent': user_agent}

    cookie_filename = 'cookie.txt'
    cookie = http.cookiejar.LWPCookieJar(cookie_filename)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)

    request = urllib.request.Request(URL_ROOT, postdata, headers)

    try:
        response = opener.open(request).read().decode("UTF-8")
    except urllib.error.URLError as e:
        print(e.reason)

    cookie.save(ignore_discard=True, ignore_expires=True)  # 保存cookie到cookie.txt中
    for item in cookie:
        print('Name = ' + item.name)
        print('Value = ' + item.value)


def localPy():
    cookie_filename = 'cookie.txt'
    cookie = http.cookiejar.MozillaCookieJar(cookie_filename)
    cookie.load(cookie_filename, ignore_discard=True, ignore_expires=True)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    get_url = 'http://www.jobbole.com/'  # 利用cookie请求访问另一个网址
    get_request = urllib.request.Request(get_url)
    get_response = opener.open(get_request)
    print(get_response.read().decode())

http_headers = { 'Accept': '*/*','Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'}


def get_real_url(url,try_count = 1):
    if try_count > 3:
        return url
    try:
        rs = requests.get(url,headers=http_headers,timeout = 10)
        if rs.status_code > 400:
            return get_real_url(url,try_count+1)
        return rs.url
    except:
        return get_real_url(url, try_count + 1)



if __name__ == "__main__":
    print(get_real_url("https://www.sex.com/video/stream/826844"))
